package chap13;
import java.util.ArrayList;

public class DVDList
{
    private DVDNode list;

    //----------------------------------------------------------------
    //  Sets up an initially empty list of magazines.
    //----------------------------------------------------------------
    public DVDList()
    {
        list = null;
    }

    //----------------------------------------------------------------
    //  Creates a new MagazineNode object and adds it to the end of
    //  the linked list.
    //----------------------------------------------------------------
    public void add(DVD dvd)
    {
        DVDNode node = new DVDNode(dvd);
        DVDNode current;

        if (list == null)
            list = node;
        else
        {
            current = list;
            while (current.next != null)
                current = current.next;
            current.next = node;
        }
    }

    public void insert(int index , DVD newdvd)
    {
        int x = 0;
        DVDNode node = new DVDNode(newdvd);
        DVDNode current = list;

        if (list == null)
            list = node;
        else  if (index == 0)
        {
            node.next = current;
            list = node;
        }

        else {
            while (x < index - 1 && current.next != null) {
                current = current.next;
                x++;
            }
            node.next = current.next;
            current.next = node;

        }
    }

    public void delete(DVD newdvd)
    {
        DVDNode node = new DVDNode(newdvd);
        DVDNode current = list;
        DVDNode prev = list;

        while (current.next != null) {
            current = current.next;
            if (current.dvd.toString().equals(node.dvd.toString())) {
                prev.next = current.next;
            } else {
                prev = current;
            }

        }
        if (!current.dvd.toString().equals(node.dvd.toString()))
            System.out.println("找不到节点，删除失败。");
    }


    //----------------------------------------------------------------
    //  Returns this list of magazines as a string.
    //----------------------------------------------------------------
    public String toString()
    {
        String result = "";

        DVDNode current = list;

        while (current != null)
        {
            result += current.dvd + "\n";
            current = current.next;
        }

        return result;
    }


    private class DVDNode
    {
        public DVD dvd;
        public DVDNode next;

        public DVDNode(DVD dvd)
        {
            this.dvd = dvd;
            next = null;
        }
    }

}


